﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc.Html;
using System.Web.Mvc;
using System.Web.Routing;
using System.Linq.Expressions;
using System.Collections;
using System.Web.Helpers;

namespace Tunynet.Mvc
{
    /// <summary>
    /// 下拉扩展
    /// </summary>
    public static class HtmlHelperDropDownListFor 
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <param name="selectList"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, ArrayList selectList, object htmlAttributes) {
            if (selectList == null) return new MvcHtmlString(""); ;

            List<SelectListItem> selectListItems = new List<SelectListItem>();
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            object[] arr=selectList.ToArray();
            if (arr.Length > 0)
            {
                for (int i = 0; i < arr.Length; i++)
                {
                   var temp=  new SelectListItem();
                   temp.Text = temp.Value = arr[i].ToString();
                   if (metadata.Model!=null&&metadata.Model.ToString() == temp.Text)
                   {
                       temp.Selected = true;
                   }
                   selectListItems.Add(temp);
                }
                return htmlHelper.DropDownListFor(expression, selectListItems, htmlAttributes);
            }
            return new MvcHtmlString("");


        }
    }
}
